package com.x.attendance.assemble.control.service;

import java.util.Date;
import java.util.List;

import com.x.attendance.core.entity.AttendanceRecord;
import com.x.attendance.core.entity.Employee;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;

/**
 * O2OA系统集成服务
 * @author Manus AI
 */
public class O2OAIntegrationService {

	private static Logger logger = LoggerFactory.getLogger(O2OAIntegrationService.class);

	/**
	 * 推送考勤数据到O2OA人事系统
	 */
	public void pushAttendanceToO2OA(List<AttendanceRecord> records) {
		for (AttendanceRecord record : records) {
			try {
				// 获取员工信息
				Employee employee = getEmployeeById(record.getEmployeeId());
				if (employee == null || employee.getO2oaPersonId() == null) {
					logger.warn("员工信息不存在或未关联O2OA人员: {}", record.getEmployeeId());
					continue;
				}

				// 转换为O2OA考勤数据格式
				O2OAAttendanceData data = convertToO2OAFormat(record, employee);
				
				// 调用O2OA API提交考勤数据
				boolean success = submitAttendanceToO2OA(data);
				
				// 更新同步状态
				updateRecordSyncStatus(record, success);
				
			} catch (Exception e) {
				logger.error("推送考勤数据失败: 记录ID=" + record.getId(), e);
				updateRecordSyncStatus(record, false, e.getMessage());
			}
		}
	}

	/**
	 * 同步O2OA人员信息到考勤系统
	 */
	public void syncPersonFromO2OA() {
		try {
			// 调用O2OA API获取人员信息
			List<O2OAPerson> persons = getPersonsFromO2OA();
			
			try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
				emc.beginTransaction(Employee.class);
				
				for (O2OAPerson person : persons) {
					// 查找现有员工记录
					List<Employee> existingEmployees = emc.listEqual(Employee.class, 
						Employee.o2oaPersonId_FIELDNAME, person.getId());
					
					Employee employee;
					if (existingEmployees.isEmpty()) {
						// 创建新员工记录
						employee = new Employee();
						employee.setO2oaPersonId(person.getId());
						employee.setEmployeeId(person.getEmployeeNumber());
					} else {
						// 更新现有员工记录
						employee = existingEmployees.get(0);
					}
					
					// 更新员工信息
					employee.setName(person.getName());
					employee.setDepartment(person.getDepartmentName());
					employee.setPosition(person.getPositionName());
					employee.setPhone(person.getMobile());
					employee.setEnabled(true);
					
					if (existingEmployees.isEmpty()) {
						emc.persist(employee);
					} else {
						emc.check(employee, Employee.class);
					}
				}
				
				emc.commit();
				logger.info("O2OA人员信息同步完成: 同步人数={}", persons.size());
			}
			
		} catch (Exception e) {
			logger.error("同步O2OA人员信息失败", e);
		}
	}

	/**
	 * 获取员工信息
	 */
	private Employee getEmployeeById(String employeeId) {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			return emc.find(employeeId, Employee.class);
		} catch (Exception e) {
			logger.error("获取员工信息失败: " + employeeId, e);
			return null;
		}
	}

	/**
	 * 转换为O2OA考勤数据格式
	 */
	private O2OAAttendanceData convertToO2OAFormat(AttendanceRecord record, Employee employee) {
		O2OAAttendanceData data = new O2OAAttendanceData();
		
		data.setPersonId(employee.getO2oaPersonId());
		data.setPersonName(employee.getName());
		data.setAttendanceTime(record.getPunchTime());
		data.setAttendanceType(convertAttendanceType(record.getPunchType()));
		data.setVerifyMode(record.getVerifyMode());
		data.setRemark(record.getRemark());
		data.setSourceSystem("考勤设备");
		
		return data;
	}

	/**
	 * 转换考勤类型
	 */
	private String convertAttendanceType(String punchType) {
		switch (punchType) {
			case "IN": return "上班";
			case "OUT": return "下班";
			case "BREAK_OUT": return "外出";
			case "BREAK_IN": return "返回";
			case "OVERTIME_IN": return "加班开始";
			case "OVERTIME_OUT": return "加班结束";
			default: return "其他";
		}
	}

	/**
	 * 提交考勤数据到O2OA
	 */
	private boolean submitAttendanceToO2OA(O2OAAttendanceData data) {
		try {
			// 这里应该调用O2OA的考勤API
			// 由于没有具体的API文档，这里使用模拟实现
			
			// 模拟API调用
			logger.info("提交考勤数据到O2OA: 人员={}, 时间={}, 类型={}", 
				data.getPersonName(), data.getAttendanceTime(), data.getAttendanceType());
			
			// 实际实现中应该调用类似以下的代码：
			// O2OAApiClient apiClient = new O2OAApiClient();
			// return apiClient.submitAttendance(data);
			
			return true; // 模拟成功
		} catch (Exception e) {
			logger.error("提交考勤数据到O2OA失败", e);
			return false;
		}
	}

	/**
	 * 获取O2OA人员信息
	 */
	private List<O2OAPerson> getPersonsFromO2OA() {
		// 这里应该调用O2OA的人员API
		// 由于没有具体的API文档，这里返回空列表
		
		// 实际实现中应该调用类似以下的代码：
		// O2OAApiClient apiClient = new O2OAApiClient();
		// return apiClient.getPersons();
		
		return new ArrayList<>();
	}

	/**
	 * 更新记录同步状态
	 */
	private void updateRecordSyncStatus(AttendanceRecord record, boolean success) {
		updateRecordSyncStatus(record, success, null);
	}

	/**
	 * 更新记录同步状态
	 */
	private void updateRecordSyncStatus(AttendanceRecord record, boolean success, String errorMessage) {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			emc.beginTransaction(AttendanceRecord.class);
			
			AttendanceRecord existingRecord = emc.find(record.getId(), AttendanceRecord.class);
			if (existingRecord != null) {
				existingRecord.setSyncStatus(success ? "SYNCED" : "FAILED");
				existingRecord.setSyncTime(new Date());
				if (errorMessage != null) {
					existingRecord.setRemark(errorMessage);
				}
				emc.check(existingRecord, AttendanceRecord.class);
			}
			
			emc.commit();
		} catch (Exception e) {
			logger.error("更新记录同步状态失败: " + record.getId(), e);
		}
	}

	/**
	 * O2OA考勤数据类
	 */
	public static class O2OAAttendanceData {
		private String personId;
		private String personName;
		private Date attendanceTime;
		private String attendanceType;
		private String verifyMode;
		private String remark;
		private String sourceSystem;

		// Getters and Setters
		public String getPersonId() {
			return personId;
		}

		public void setPersonId(String personId) {
			this.personId = personId;
		}

		public String getPersonName() {
			return personName;
		}

		public void setPersonName(String personName) {
			this.personName = personName;
		}

		public Date getAttendanceTime() {
			return attendanceTime;
		}

		public void setAttendanceTime(Date attendanceTime) {
			this.attendanceTime = attendanceTime;
		}

		public String getAttendanceType() {
			return attendanceType;
		}

		public void setAttendanceType(String attendanceType) {
			this.attendanceType = attendanceType;
		}

		public String getVerifyMode() {
			return verifyMode;
		}

		public void setVerifyMode(String verifyMode) {
			this.verifyMode = verifyMode;
		}

		public String getRemark() {
			return remark;
		}

		public void setRemark(String remark) {
			this.remark = remark;
		}

		public String getSourceSystem() {
			return sourceSystem;
		}

		public void setSourceSystem(String sourceSystem) {
			this.sourceSystem = sourceSystem;
		}
	}

	/**
	 * O2OA人员信息类
	 */
	public static class O2OAPerson {
		private String id;
		private String name;
		private String employeeNumber;
		private String departmentName;
		private String positionName;
		private String mobile;

		// Getters and Setters
		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getEmployeeNumber() {
			return employeeNumber;
		}

		public void setEmployeeNumber(String employeeNumber) {
			this.employeeNumber = employeeNumber;
		}

		public String getDepartmentName() {
			return departmentName;
		}

		public void setDepartmentName(String departmentName) {
			this.departmentName = departmentName;
		}

		public String getPositionName() {
			return positionName;
		}

		public void setPositionName(String positionName) {
			this.positionName = positionName;
		}

		public String getMobile() {
			return mobile;
		}

		public void setMobile(String mobile) {
			this.mobile = mobile;
		}
	}
}

